package com.qf.smsplatform.search.service.impl;

import com.qf.smsplatform.common.index.StandardSubmit;
import com.qf.smsplatform.search.service.SearchService;
import com.qf.smsplatform.search.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    private  final String INDEX = "sms_submit_log_";

    private  final String TYPE = "sms_submit_log_type";
    @Override
    public void add(StandardSubmit submit) throws IOException {

        String yyyy = new SimpleDateFormat("yyyy").format(new Date());

        //创建request对象
        IndexRequest request = new IndexRequest(INDEX+yyyy,TYPE,submit.getSequenceld());

        //封装request对象信息
        request.source(JsonUtils.object2Map(submit));

        //通过client发送请求到es
        IndexResponse index = client.index(request, RequestOptions.DEFAULT);

        //获取返回结果
        if (!"CREATED".equalsIgnoreCase(index.getResult().toString())){
            log.error("【搜索模块】 添加数据失败 index={},type={},submit={}",INDEX,TYPE,submit);
            throw  new  RuntimeException("【搜索模块】 添加数据失败");
        }



        //判断是否添加成功

    }
}
